import HtmlWebpackPlugin from "html-webpack-plugin"
import { join, dirname, parse } from 'node:path'
import { fileURLToPath } from 'node:url';
import fs from "fs"

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const htmlFiles = []
function findHTMLFiles(dirPath, prePathName) {

    const files = fs.readdirSync(dirPath, { withFileTypes: true })

    files.forEach(file => {
        const fullPath = join(dirPath, file.name);
        if (file.isDirectory()) {
            findHTMLFiles(fullPath, join(prePathName, file.name));
        }
        else if (file.name.endsWith('.html')) {
            htmlFiles.push({ fullPath, dirPath, name: file.name, prePathName });
        }
    });
}

findHTMLFiles(join(__dirname, "src"), "")

const plugins = htmlFiles.map(p => {
    const parseData = p
    console.log(parseData)
    return new HtmlWebpackPlugin({
        template: p.fullPath, // 使用模板
        filename: join(parseData.prePathName || "", parseData.name), //  打包后的文件名
        chunks: ['main'], // 对应html模板想要引入对应打包入口打包后的js包，这里就需要和entry key一一对应
        inject: true, // 默认注入所有静态资源
        minify: {
            html5: true,
            collapsableWhitespace: true,
            preserveLineBreaks: false,
            minifyCSS: true,
            minifyJS: true,
            removeComments: false,
            collapseWhitespace: true,
        }
    })
})


export default {
    mode: "production", // production development
    output: {
        path: join(__dirname, 'dist'),
        filename: '[name].js'
    },
    module: {
        rules: [
            {
                test: /\.htm$/i,
                loader: 'html-loader',
            }, {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            }
        ],
    },
    plugins,
    devServer: {
        static: {
            directory: join(__dirname, 'dist'),
        },
        compress: true,
        port: 9000,
    },
};